Completed
Pull Request — master (#79)
by Johan
01:10
created

shared.js ➔ getBarcodePadding   B

Complexity

Conditions 6
Paths 5

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
c 1
b 0
f 0
nc 5
nop 3
dl 0
loc 14
rs 8.8571
1
import merge from "../help/merge.js";
2
3
function getEncodingHeight(encoding, options){
4
	return options.height +
5
		((options.displayValue && encoding.text.length > 0) ? options.fontSize : 0) +
6
		options.textMargin +
7
		options.marginTop +
8
		options.marginBottom;
9
}
10
11
function getBarcodePadding(textWidth, barcodeWidth, options){
12
	if(options.displayValue && barcodeWidth < textWidth){
13
		if(options.textAlign == "center"){
14
			return Math.floor((textWidth - barcodeWidth) / 2);
15
		}
16
		else if(options.textAlign == "left"){
17
			return 0;
18
		}
19
		else if(options.textAlign == "right"){
20
			return Math.floor(textWidth - barcodeWidth);
21
		}
22
	}
23
	return 0;
24
}
25
26
function calculateEncodingAttributes(encodings, barcodeOptions, context){
27
	for(let i = 0; i < encodings.length; i++){
28
		var encoding = encodings[i];
29
		var options = merge(barcodeOptions, encoding.options);
30
31
		// Calculate the width of the encoding
32
		var textWidth = messureText(encoding.text, options, context);
33
		var barcodeWidth = encoding.data.length * options.width;
34
		encoding.width =  Math.ceil(Math.max(textWidth, barcodeWidth));
35
36
		encoding.height = getEncodingHeight(encoding, options);
37
38
		encoding.barcodePadding = getBarcodePadding(textWidth, barcodeWidth, options);
39
	}
40
}
41
42
function getTotalWidthOfEncodings(encodings){
43
	var totalWidth = 0;
44
	for(let i = 0; i < encodings.length; i++){
45
		totalWidth += encodings[i].width;
46
	}
47
	return totalWidth;
48
}
49
50
function getMaximumHeightOfEncodings(encodings){
51
	var maxHeight = 0;
52
	for(let i = 0; i < encodings.length; i++){
53
		if(encodings[i].height > maxHeight){
54
			maxHeight = encodings[i].height;
55
		}
56
	}
57
	return maxHeight;
58
}
59
60
function messureText(string, options, context){
61
	var ctx;
62
	if(typeof context === "undefined"){
63
		ctx = document.createElement("canvas").getContext("2d");
64
	}
65
	else{
66
		ctx = context;
67
	}
68
69
	ctx.font = options.fontOptions + " " + options.fontSize + "px " + options.font;
70
71
	// Calculate the width of the encoding
72
	var size = ctx.measureText(string).width;
73
74
	return size;
75
}
76
77
export {getMaximumHeightOfEncodings, getEncodingHeight, getBarcodePadding, calculateEncodingAttributes, getTotalWidthOfEncodings};
78